package com.xuebank.nfe.nfecar.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.support.annotation.IdRes
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.widget.*
import com.trello.rxlifecycle.android.ActivityEvent
import com.wzn.libaray.event.RxBus
import com.wzn.libaray.utils.Logger
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.*
import com.xuebank.nfe.nfecar.adapter.GridImageAdapter
import com.xuebank.nfe.nfecar.beas.BaseActivity
import com.xuebank.nfe.nfecar.config.PictureConfig
import com.xuebank.nfe.nfecar.config.PictureMimeType
import com.xuebank.nfe.nfecar.dialog.PictureDialog
import com.xuebank.nfe.nfecar.entity.LocalMedia
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.model.*
import com.xuebank.nfe.nfecar.model.base.BaseModel
import com.xuebank.nfe.nfecar.permissions.RxPermissions
import com.xuebank.nfe.nfecar.tools.PictureFileUtils
import com.xuebank.nfe.nfecar.utils.network.ServiceGenerator
import com.xuebank.nfe.nfecar.utils.network.service.CommonService
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.util.ArrayList

/**
 * 发布页面
 */
class ReleaseActivity : BaseActivity(), View.OnClickListener,
        RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener {


    private var selectList: MutableList<LocalMedia> = ArrayList()
    private var mTagViewBodel: TagViewBodel? = null
    private var mTagGroupModel: TagGroupModel? = null
    private var recyclerView: RecyclerView? = null
    private var mImagePathModel: ImagePathModel? = null
    private var adapter: GridImageAdapter? = null
    private var maxSelectNum = 9
    private var themeId: Int = 0
    private val chooseMode = PictureMimeType.ofAll()
    var from: String? = null
    var image: String? = null
    private var mTagViewListModel: TagViewListModel? = null
    private var mImageButton: ImageButton? = null
    private var mFaBuTv: TextView? = null
    private var mCaoGaoTv: TextView? = null
    private var mETTv: EditText? = null
    private var mLocalMedia: LocalMedia? = null
    private var mUploadDataModel: UploadDataModel? = null//发布接口传参
    private var mBlogMultimediaList: BlogMultimediaList? = null
    private var mUploadDataModels: UploadDataModels? = null
    private var mUploadDataModelss: UploadDataModelss? = null
    private var mTagList: TagList? = null
    private var mTagViewListModels: TagViewListModels? = null
    protected var compressDialog: PictureDialog? = null
    private var mTagIntI: TagIntI? = null
    var j: Int? = 0

    var dd: uploadImageI? = null
    var misPublish: isPublishModel? = null
    var misPublish_No: noPublishModel? = null
    var goin :Int ?=0
    var isPublish:Boolean? =true
    var isPublishsss:Boolean?=true
    var noteId:String? =""
    var blogId:Int? =0
    var type:Int? = 0

    val mFrontBackData:FrontBackData? = FrontBackData()//车记详情拉下来的数据
    val mBlogMultimediaLists:BlogMultimediaLists? = BlogMultimediaLists()//车记详情拉下来的数据中的标签list


    override fun findViews() {
        super.findViews()
        recyclerView = findViewById(R.id.recycler) as RecyclerView


        mImageButton = findViewById(R.id.fabu_back)
        mFaBuTv = findViewById(R.id.fabu_fabu)
        mCaoGaoTv = findViewById(R.id.fabu_caogao)
        mETTv = findViewById(R.id.fabu_et)


        mImageButton?.setOnClickListener(this)
        mFaBuTv?.setOnClickListener(this)
        mCaoGaoTv?.setOnClickListener(this)
        mETTv?.setOnClickListener(this)

        mTagViewListModel = TagViewListModel()
        mTagViewListModels = TagViewListModels()
        mUploadDataModel = UploadDataModel()
        mUploadDataModels = UploadDataModels()
        mUploadDataModelss = UploadDataModelss()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        this.finish()
    }

    companion object {

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_release)
        from = intent.getStringExtra(Constants.LOGIN_RELEASE)
        if (from == Constants.ALBUM) {            //从拍照进来的

            if (intent.getStringExtra("Imagepath") != null) {
                //拍照跳转过来随后跳转照片预览
                image = intent.getStringExtra("Imagepath")
                val intent = Intent(this, PicturePreviewActivity::class.java)
                intent.putExtra("hhaha", "hahaw")
                intent.putExtra("Imagepath", image)
                startActivityForResult(intent, 1111)
            } else {
                //相机页面跳转过来去相册
                goPictureSelectorActivity()
            }
        } else if (intent.getStringExtra("path") != null) {
            //拍摄视频跳转过来
            mLocalMedia = LocalMedia()
            mLocalMedia?.path = intent.getStringExtra("path")
            selectList.add(mLocalMedia!!)
            mTagViewBodel = TagViewBodel()

            maxSelectNum = 1

            mTagViewBodel?.path = intent.getStringExtra("path")
            mTagViewListModels?.tagViewBodel?.add(mTagViewBodel!!)
        } else if (from == Constants.DRAFT) {  //从H5过来的
            if (goin == 0) {

                 noteId = intent.getStringExtra("noteId")
                isPublish = intent.getBooleanExtra("isPublish", true)
                if (isPublish == true) {
                    showCompressDialog()
                    isPublish(noteId ?: "")
                } else {
                    showCompressDialog()
                    isPublish_caogao(noteId ?: "")
                }
                goin=1
                RxBus.getDefault().post("NoAdd")

            }
        }


        themeId = R.style.picture_default_style
        val manager = FullyGridLayoutManager(this@ReleaseActivity, 4, GridLayoutManager.VERTICAL, false)
        recyclerView?.setLayoutManager(manager)
        adapter = GridImageAdapter(this@ReleaseActivity, onAddPicClickListener)
        adapter?.setList(selectList)

        adapter?.setSelectMax(maxSelectNum)
        recyclerView?.setAdapter(adapter)
        if (goin == 1) {
            RxBus.getDefault().post("NoAdd")
            adapter?.notifyDataSetChanged()
        }

        val intentsss = Intent(this, NativeVideoPlayerActivity::class.java)
        adapter?.setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, v: View) {
                if (mTagViewListModels?.tagViewBodel?.get(0)?.path?.contains(".mp4")!!) {
                    intentsss.putExtra("path", mTagViewListModels?.tagViewBodel?.get(0)?.path)
                    intentsss.putExtra("isVideo", "isVideo")
                    startActivityForResult(intentsss, 3333)
                } else {
                    val intents = Intent(this@ReleaseActivity, PicturePreviewActivity::class.java)
                    val  mssss = TagViewListModel()
                    for (i in 0..(mTagViewListModels?.tagViewBodel?.size ?: 0).minus(1)) {
                        mTagViewBodel = TagViewBodel()
                        if (mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.size != 0) {

                            for (e in 0..((mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.size)?.minus(1) ?: 0)) {

                                mTagGroupModel=TagGroupModel()


                                mTagGroupModel?.percentX = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(e)?.percentX ?: 0f
                                mTagGroupModel?.percentY = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(e)?.percentY ?: 0f

                               val mTAgs = TagGroupModel.Tag()
                                mTAgs.direction = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(e)?.tags?.get(0)?.direction?:0
                                mTAgs.id = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(e)?.tags?.get(0)?.id?:0
                                mTAgs.name = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(e)?.tags?.get(0)?.name
                                mTagGroupModel?.tags?.add(mTAgs)

                                mTagViewBodel?.tabText?.add(mTagGroupModel!!)
                                intents.putExtra("ImageListssssss",mTagGroupModel)

                            }
                        }
                        mTagViewBodel?.path = mTagViewListModels?.tagViewBodel?.get(i)?.path

                        mssss.tagViewBodel?.add(mTagViewBodel!!)
                    }


//                    val b  = Bundle()
//                    b.putParcelable("ImageList",mTagViewListModel)
//                    intents.putExtras(b)
                    intents.putExtra("ImageList",mssss)
                    intents.putExtra("eeeee","eeeee")
                    startActivity(intents)
                    mTagViewListModels?.tagViewBodel?.clear()

//                    RxBus.getDefault().post(mTagViewListModel)

                }
            }
        })

        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        val permissions = RxPermissions(this)
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(object : Observer<Boolean> {
            override fun onSubscribe(d: Disposable) {}

            override fun onNext(aBoolean: Boolean?) {
                if (aBoolean!!) {
                    PictureFileUtils.deleteCacheDirFile(this@ReleaseActivity)
                } else {
                    Toast.makeText(this@ReleaseActivity,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show()
                }
            }

            override fun onError(e: Throwable) {}

            override fun onComplete() {}
        })


    }

    /**
     * 拉取从h5归来的草稿id，获取草稿详情
     */
    fun isPublish_caogao(noteId: String) {
        //拉取从H5传过来的id   获取详情信息
        misPublish_No = noPublishModel()
        misPublish_No?.id = noteId.toInt()
        ServiceGenerator.createService(CommonService::class.java)
                .caogaoxiangqing(misPublish_No!!)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe({
                    if (it?.isOk()!!) {
                        dismissCompressDialog()
                        if (it.result?.blogMultimediaList?.get(0)?.url?.contains("mp4")!!) {
                            maxSelectNum = 1
                        } else {
                            maxSelectNum = 9
                        }
                        for (i in 0..(it.result?.blogMultimediaList?.size?.minus(1) ?: 0)) {
                            val mTagViewBodel = TagViewBodel()
                            val mLocalMedia = LocalMedia()
                            mLocalMedia.path = it.result?.blogMultimediaList?.get(i)?.url
                            selectList.add(mLocalMedia)
                            for (q in 0..(it.result?.blogMultimediaList?.get(i)?.tagList?.size?.minus(1) ?: 0)) {
                                val mTagGroupModel = TagGroupModel()
                                val mTag = TagGroupModel.Tag()
                                mTag.name = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.content
                                mTag.direction = getUpLoadDirection(it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.direction ?: "")
                                mTag.id = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.tagId ?: 0
                                mTagGroupModel.tags?.add(mTag)
                                mTagGroupModel.percentX = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.positionX ?: 0f
                                mTagGroupModel.percentY = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.positionY ?: 0f
                                mTagViewBodel.tabText?.add(mTagGroupModel)
                            }
                            mTagViewBodel.path = it.result?.blogMultimediaList?.get(i)?.url
                            mTagViewListModels?.tagViewBodel?.add(mTagViewBodel)
                        }
                        mETTv?.setText(it.result?.content)
                        type = it.result?.type
                        blogId = it.result?.blogId
                        adapter?.setSelectMax(maxSelectNum)
                        adapter?.setList(selectList)
                        adapter?.notifyDataSetChanged()

                    } else {
                        Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                    }
                }, {
                    Logger.d("错误信息", "it.message${it.message}")
                })
    }

    fun isPublish(noteId: String) {
        //拉取从H5传过来的id   获取详情信息
        misPublish = isPublishModel()
        misPublish?.id = noteId.toInt()
        ServiceGenerator.createService(CommonService::class.java)
                .isPublish(misPublish!!)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe({
                    if (it?.isOk()!!) {
                        dismissCompressDialog()
                        if (it.result?.blogMultimediaList?.get(0)?.url?.contains("mp4")!!) {
                            maxSelectNum = 1
                        } else {
                            maxSelectNum = 9
                        }
                        for (i in 0..(it.result?.blogMultimediaList?.size?.minus(1) ?: 0)) {
                            val mTagViewBodel = TagViewBodel()
                            val mLocalMedia = LocalMedia()
                            mLocalMedia.path = it.result?.blogMultimediaList?.get(i)?.url
                            selectList.add(mLocalMedia)
                            for (q in 0..(it.result?.blogMultimediaList?.get(i)?.tagList?.size?.minus(1) ?: 0)) {
                                val mTagGroupModel = TagGroupModel()
                                val mTag = TagGroupModel.Tag()
                                mTag.name = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.content
                                mTag.direction = getUpLoadDirection(it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.direction ?: "")
                                mTag.id = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.tagId ?: 0
                                mTagGroupModel.tags?.add(mTag)
                                mTagGroupModel.percentX = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.positionX ?: 0f
                                mTagGroupModel.percentY = it.result?.blogMultimediaList?.get(i)?.tagList?.get(q)?.positionY ?: 0f
                                mTagViewBodel.tabText?.add(mTagGroupModel)
                            }
                            mTagViewBodel.path = it.result?.blogMultimediaList?.get(i)?.url
                            mTagViewListModels?.tagViewBodel?.add(mTagViewBodel)
                        }
                        type = it.result?.type
                        adapter?.setSelectMax(maxSelectNum)
                        adapter?.setList(selectList)
                        adapter?.notifyDataSetChanged()
                        mETTv?.setText(it.result?.content)

                    } else {
                        Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                    }
                }, {
                    Logger.d("错误信息", "it.message${it.message}")
                })

    }

    fun noPublish(noteId: String) {
        mBlogMultimediaList = BlogMultimediaList()
        for (i in 0..(mTagViewListModels?.tagViewBodel?.size?.minus(1) ?: 0)) {
            for (k in 0..((mTagViewListModels?.tagViewBodel?.get(i )?.tabText?.size ?: 0) - 1)) {
                mTagList = TagList()

                mTagList?.tagId = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.tags?.get(0)?.id
                mTagList?.direction = setUpLoadDirection(mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.tags?.get(0)?.direction ?: 0)
                mTagList?.type = 0

                mTagList?.positionX = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.percentX
                mTagList?.positionY = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.percentY


//                            mTagLists?.add(mTagList!!)
                mBlogMultimediaList?.tagList?.add(mTagList!!)
            }


            mBlogMultimediaList?.sort = (i)

//                        mBlogMultimediaList?.tagList=mTagLists
            mBlogMultimediaList?.url = mTagViewListModels?.tagViewBodel?.get(i)?.path

            mUploadDataModelss?.blogMultimediaList?.add(mBlogMultimediaList!!)
            mUploadDataModelss?.id= noteId.toInt()
            mUploadDataModelss?.type =type
            if (blogId != null) {
                mUploadDataModelss?.blogId =blogId
            }
            mUploadDataModelss?.content = mETTv?.text.toString()
        }

        gofab(mUploadDataModelss!!)
    }

    override fun initViews() {
        super.initViews()

        RxBus.getDefault().toObserverable(TagViewListModels::class.java)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe({ reques ->
                    if (reques.tagViewBodel?.size != 0) {
                        for (i in 0..(reques.tagViewBodel?.size ?: 0) - 1) {
                            mTagViewListModels?.tagViewBodel?.add(reques.tagViewBodel?.get(i)!!)
                        }
                    }
                })

        RxBus.getDefault().toObserverable(ImagePathModel::class.java)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe { reques ->

                }

        RxBus.getDefault().toObserverable(uploadImageI::class.java)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe({ reques ->


                    if (reques.i.compareTo((mTagViewListModels?.tagViewBodel?.size ?: 0) - 1) < 0) {

                        j = j?.plus(1)
                        uploadImageEnd()
                    } else {
                        Logger.d(TAG, "mUploadDataModel   ${mUploadDataModel}")
                        mUploadDataModel?.type = 0
                        mUploadDataModel?.content = mETTv?.text.toString() ?: ""

                        if (mUploadDataModel != null) {
                            fabu(mUploadDataModel!!)
                        }
                        Logger.d("上传的数据","数据为：  ${mUploadDataModel}")
                    }
                })


        RxBus.getDefault().toObserverable(DeleteTagListSizeList::class.java)
                .subscribe({
                    reques ->
                    for (i in 0..(reques.mDeleteTagListSize?.size?.minus(1) ?: 0)) {
                        for (e  in 0..(mTagViewListModels?.tagViewBodel?.size?.minus(1)?:0)){
                            if (reques.mDeleteTagListSize?.get(i)?.imagePosition==e){
                                mTagViewListModels?.tagViewBodel?.get(e)?.tabText?.removeAt(reques.mDeleteTagListSize?.get(i)?.TagPosition?:0)
                            }

                        }

                    }

                })



        adapter?.notifyDataSetChanged()

    }


    private val onAddPicClickListener = object : GridImageAdapter.onAddPicClickListener {
        override fun onAddPicClick() {
            goPictureSelectorActivity()

        }

    }

    override fun onResume() {
        super.onResume()


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode != null) {

                when (requestCode) {
                    PictureConfig.CHOOSE_REQUEST -> {
                        // 图片选择结果回调
                        var selectListss: MutableList<LocalMedia> = ArrayList()
                        selectListss = PictureSelector.obtainMultipleResult(data)
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                        // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                        for (media in selectList) {
                            Log.i("图片-----》", media.path)
                        }
                        for (i in 0..selectListss.size - 1) {
                            selectList.add(selectListss.get(i))
                        }
                        if (selectList.size == mTagViewListModels?.tagViewBodel?.size ?: 0) {

                            for (f in 0..selectList.size - 1) {
                                if (f == 0) {
                                    val bitmap = BitmapFactory.decodeFile(selectList[f].path)
                                    var height = bitmap.width * 1.3
                                    if (bitmap.width * 1.3 > bitmap.height) {
                                        height = bitmap.height.toDouble()
                                    } else {
                                        height = bitmap.width * 1.3
                                    }
                                    val jjjjj = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, (height).toInt(), null, false)
                                    jjjjj.height
                                    mTagViewListModels?.tagViewBodel?.get(f)?.path = PictureBaseActivity.saveBitmap(this, jjjjj)
                                } else {
                                    val bitmap = BitmapFactory.decodeFile(selectList[f].compressPath)
                                    var height = bitmap.width * 1.3
                                    if (bitmap.width * 1.3 > bitmap.height) {
                                        height = bitmap.height.toDouble()
                                    } else {
                                        height = bitmap.width * 1.3
                                    }
                                    val jjjjj = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, (height).toInt(), null, false)
                                    jjjjj.height
                                    mTagViewListModels?.tagViewBodel?.get(f)?.path = PictureBaseActivity.saveBitmap(this, jjjjj)
                                }

                            }


                        } else {
                            if (selectList.get(0).path.contains(".mp4")) {
                                mTagViewBodel = TagViewBodel()
                                mTagViewBodel?.path = selectList.get(0).path
                                mTagViewListModels?.tagViewBodel?.add(mTagViewBodel!!)
//                                mTagViewListModels?.tagViewBodel?.get(0)?.path = selectList[0].path
                            }
                        }
                        if (mTagViewListModels?.tagViewBodel?.get(0)?.path != null) {
                            if (mTagViewListModels?.tagViewBodel?.get(0)?.path?.contains(".mp4") != false) {
                                maxSelectNum = 1
                            } else {
                                maxSelectNum = 9
                            }
                        }
                        adapter?.setSelectMax(maxSelectNum)


                        adapter?.setList(selectList)
                        adapter?.notifyDataSetChanged()
                    }
                    1111 -> {

                        //拍照过来的

                        val bundle = data?.getStringExtra("skjnkejnre")

                        mLocalMedia = LocalMedia()
                        mLocalMedia?.path = bundle

                        selectList.add(mLocalMedia!!)

                        if (mTagViewListModels?.tagViewBodel?.get(0)?.path != null) {

                        } else {
                            mTagViewBodel = TagViewBodel()
                            mTagViewBodel?.path = bundle
                            mTagViewListModels?.tagViewBodel?.add(mTagViewBodel!!)
                            Logger.d(TAG, "mTagViewListModel${mTagViewListModel}")
                            adapter?.setList(selectList)
                        }


                        adapter?.notifyDataSetChanged()
                    }
                    2222 -> {

                    }
                    3333 -> {
                        //拍摄视频进入此页面有预览点击确认回到此页面
                        val isVideo = data?.getStringExtra("path")
//                        mTagViewBodel = TagViewBodel()
//                        mTagViewBodel?.path = selectList.get(0).path
//                        mTagViewListModels?.tagViewBodel?.add(mTagViewBodel!!)
                    }
                }
            }
        }
    }

    fun imageOrVideo(path: String): Int {
        if (path.contains("jpg") || path.contains("jpeg") || path.contains("png") || path.contains("webp") || path.contains("gif") || path.contains("bmp")) {
            return 0
        } else {
            return 1
        }
    }


    override fun onClick(v: View) {


        when (v.id) {



            R.id.fabu_back -> {//返回按钮
                this.finish()
            }
            R.id.fabu_fabu -> {//发布按钮
                isPublishsss = true
                showCompressDialog()

                if (goin == 1) {
                    if (isPublish == true) {
                        obtainData()
                    } else {
                        noPublish(noteId?:"")
                    }

                } else {

                    if (imageOrVideo(mTagViewListModels?.tagViewBodel?.get(0)?.path ?: "") == 0) {
                        uploadImageEnd()
                    } else {
                        fabuVideo()
                    }
                }

            }
            R.id.fabu_caogao -> {//存草稿按钮
                isPublishsss = false
                showCompressDialog()
                if (goin == 1) {
                    if (isPublish == false) {
                        obtainData()
                    } else {
                        carTocaogao()
                    }


                } else {

                    if (imageOrVideo(mTagViewListModels?.tagViewBodel?.get(0)?.path ?: "") == 0) {
                        uploadImageEnd()
                    } else {
                        fabuVideo()
                    }
                }
            }
            R.id.fabu_et -> { //

            }

        }
    }

    /**
     * 上传视频到草稿或者发布
     */
    fun fabuVideo() {
        //上传视频
        var file: File? = null   //图片地址
        file = File(Uri.parse(mTagViewListModels?.tagViewBodel?.get(0)?.path ?: "").toString())
        Logger.d("图片多大", "file图片的大小为${file.length().div(1024).div(1024).toFloat()}")
        upLoadVideo(file)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe({
                    if (it.isOk()) {
                        mBlogMultimediaList = BlogMultimediaList()
                        mBlogMultimediaList?.url = it.result?.url
                        mBlogMultimediaList?.sort = 0

                        mUploadDataModel?.blogMultimediaList?.add(mBlogMultimediaList!!)
                        mUploadDataModel?.type = 1
                        mUploadDataModel?.content = mETTv?.text.toString() ?: ""
                        if (mUploadDataModel != null) {
                            fabu(mUploadDataModel!!)
                        }
                    } else {
                        Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                    }
                }, {

                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                })

    }

    fun carTocaogao() {
        mBlogMultimediaList = BlogMultimediaList()
        for (i in 0..(mTagViewListModels?.tagViewBodel?.size?.minus(1) ?: 0)) {
            for (k in 0..((mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.size ?: 0) - 1)) {
                mTagList = TagList()

                mTagList?.tagId = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.tags?.get(0)?.id
                mTagList?.direction = setUpLoadDirection(mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.tags?.get(0)?.direction ?: 0)
                mTagList?.type = 0

                mTagList?.positionX = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.percentX
                mTagList?.positionY = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.percentY


//                            mTagLists?.add(mTagList!!)
                mBlogMultimediaList?.tagList?.add(mTagList!!)
            }


            mBlogMultimediaList?.sort = (i)

//                        mBlogMultimediaList?.tagList=mTagLists
            mBlogMultimediaList?.url = mTagViewListModels?.tagViewBodel?.get(i)?.path

            mUploadDataModel?.blogMultimediaList?.add(mBlogMultimediaList!!)
            mUploadDataModel?.type = type
            mUploadDataModel?.content = mETTv?.text.toString()
        }

        gocaocao(mUploadDataModel!!)

    }

    fun gocaocao(mUploadDataModel:UploadDataModel) {
        ServiceGenerator.createService(CommonService::class.java)
                .caogao(mUploadDataModel)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe({
                    if (it.isOk()) {
                        dismissCompressDialog()
                        Toast.makeText(this, "车记保存草稿成功", Toast.LENGTH_SHORT).show()
                        val intent = Intent(this, SecondActivity::class.java)
                        intent.putExtra("url", Constants.CARJI_LIST)
                        startActivity(intent)
                        this.finish()
                        finishCameraActivity()
                    } else {
                        Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                    }
                }, {
                    if (it.message.equals("该操作需要用户登录")) {
                        val intent = Intent(this,SecondActivity::class.java)
                        intent.putExtra("url",Constants.LOGIN_ADDRESS)
                        startActivity(intent)
                    }

                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                })

    }
    //保存车记草稿
    fun obtainData() {
        mBlogMultimediaList = BlogMultimediaList()
        for (i in 0..(mTagViewListModels?.tagViewBodel?.size?.minus(1) ?: 0)) {
            for (k in 0..((mTagViewListModels?.tagViewBodel?.get(i )?.tabText?.size ?: 0) - 1)) {
                mTagList = TagList()

                mTagList?.tagId = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.tags?.get(0)?.id
                mTagList?.direction = setUpLoadDirection(mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.tags?.get(0)?.direction ?: 0)
                mTagList?.type = 0

                mTagList?.positionX = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.percentX
                mTagList?.positionY = mTagViewListModels?.tagViewBodel?.get(i)?.tabText?.get(k)?.percentY


//                            mTagLists?.add(mTagList!!)
                mBlogMultimediaList?.tagList?.add(mTagList!!)
            }


            mBlogMultimediaList?.sort = (i)

//                        mBlogMultimediaList?.tagList=mTagLists
            mBlogMultimediaList?.url = mTagViewListModels?.tagViewBodel?.get(i)?.path

            mUploadDataModels?.blogMultimediaList?.add(mBlogMultimediaList!!)
            mUploadDataModels?.id= noteId?.toInt()
            mUploadDataModels?.type =type
            mUploadDataModels?.content = mETTv?.text.toString()
        }


        bianjifabu(mUploadDataModels!!)
    }


    fun gofab(UploadDataModel: UploadDataModelss) {
        ServiceGenerator.createService(CommonService::class.java)
                .caogaoGocheji(UploadDataModel)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe({
                    if (it.isOk()) {
                        dismissCompressDialog()
                        Toast.makeText(this, "再次发布车记成功", Toast.LENGTH_SHORT).show()
                        val intent = Intent(this, SecondActivity::class.java)
                        intent.putExtra("url", Constants.CARJI_LIST)
                        startActivity(intent)
                        this.finish()
                        finishCameraActivity()
                    } else {
                        Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                    }
                }, {
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                })
    }

    fun bianjifabu(UploadDataModel: UploadDataModels) {
        val header = SharedPreferencesUtil.getInstance(this).getString(MainActivity.COOKIE)
        if (isPublishsss == true) {
            ServiceGenerator.createService(CommonService::class.java)
                    .bianjifabu(UploadDataModel)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(bindToLifecycle())
                    .subscribe({
                        if (it.isOk()) {
                            dismissCompressDialog()
                            Toast.makeText(this, "再次发布车记成功", Toast.LENGTH_SHORT).show()
                            val intent = Intent(this, SecondActivity::class.java)
                            intent.putExtra("url", Constants.CARJI_LIST)
                            startActivity(intent)
                            this.finish()
                            finishCameraActivity()
                        } else {
                            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                        }
                    }, {
                        if (it.message.equals("该操作需要用户登录")) {
                            val intent = Intent(this,SecondActivity::class.java)
                            intent.putExtra("",Constants.LOGIN_ADDRESS)
                            startActivity(intent)
                        }
                        it.message
                        Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                    })
        } else {
            ServiceGenerator.createService(CommonService::class.java)
                    .bianjicaogao(UploadDataModel)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(bindToLifecycle())
                    .subscribe({
                        if (it.isOk()) {
                            dismissCompressDialog()
                            Toast.makeText(this, "再次保存草稿成功", Toast.LENGTH_SHORT).show()
                            val intent = Intent(this, SecondActivity::class.java)
                            intent.putExtra("url", Constants.CARJI_LIST)
                            startActivity(intent)
                            this.finish()
                            finishCameraActivity()
                        } else {
                            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                        }
                    }, {
                        it.message
                        Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                    })
        }


    }



    fun fabu(UploadDataModel: UploadDataModel) {
        val header = SharedPreferencesUtil.getInstance(this).getString(MainActivity.COOKIE)
        if (isPublishsss == true) {
            ServiceGenerator.createService(CommonService::class.java)
                    .fabu(UploadDataModel)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(bindToLifecycle())
                    .subscribe({
                        if (it.isOk()) {
                            dismissCompressDialog()
                            Toast.makeText(this, "发布车记成功", Toast.LENGTH_SHORT).show()
                            val intent = Intent(this, SecondActivity::class.java)
                            intent.putExtra("url", Constants.CARJI_LIST)
                            startActivity(intent)
                            this.finish()
                            finishCameraActivity()
                        } else {
                            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                        }
                    }, {
                        if (it.message.equals("该操作需要用户登录")) {
                            val intent = Intent(this,SecondActivity::class.java)
                            intent.putExtra("",Constants.LOGIN_ADDRESS)
                            startActivity(intent)

                        }
                        Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                    })
        } else {
            ServiceGenerator.createService(CommonService::class.java)
                    .caogao(UploadDataModel)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(bindToLifecycle())
                    .subscribe({
                        if (it.isOk()) {
                            dismissCompressDialog()
                            Toast.makeText(this, "保存草稿成功", Toast.LENGTH_SHORT).show()
                            val intent = Intent(this, SecondActivity::class.java)
                            intent.putExtra("url", Constants.CARJI_LIST)
                            startActivity(intent)
                            this.finish()
                            finishCameraActivity()
                        } else {
                            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                        }
                    }, {
                        if (it.message.equals("该操作需要用户登录")) {
                            val intent = Intent(this,SecondActivity::class.java)
                            intent.putExtra("",Constants.LOGIN_ADDRESS)
                            startActivity(intent)
                        }

                        Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                    })
        }


    }

    fun getUpLoadDirection(direction:String):Int{
        if (direction.equals("L")) {
            return 0
        } else {
            return 1
        }
    }

    fun setUpLoadDirection(direction: Int): String {
        if (direction == 0) {
            return "L"
        } else {
            return "R"
        }

    }

    fun uploadImage(file: File): Observable<BaseModel<VideoModel>> {
        return ServiceGenerator.createService(CommonService::class.java)
                .uploadFile(file = createPartFromFile(file, "file"), pathName = createPartFromString("pathName"))
    }

    fun upLoadVideo(file: File): Observable<BaseModel<VideoModel>> {
        return ServiceGenerator.createService(CommonService::class.java)
                .uploadVideo(file = createPartFromFile(file, "file"), pathName = createPartFromString("pathName"))
    }

    fun uploadImageEnd() {
        var file: File? = null
        file = File(Uri.parse(mTagViewListModels?.tagViewBodel?.get(j ?: 0)?.path ?: "").toString())
        Logger.d("file的大小", "file图片的大小${file.length()}")
        uploadImage(file)
                .subscribeOn(Schedulers.io())
                .compose(bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.isOk()) {

                        Logger.d(TAG, "it.code    ${it.code}")
                        mBlogMultimediaList = BlogMultimediaList()
                        for (k in 0..((mTagViewListModels?.tagViewBodel?.get(j ?: 0)?.tabText?.size ?: 0) - 1)) {
                            var mTagLists: MutableList<TagList>? = arrayListOf()
                            mTagList = TagList()

                            mTagList?.tagId = mTagViewListModels?.tagViewBodel?.get(j ?: 0)?.tabText?.get(k)?.tags?.get(0)?.id
                            mTagList?.direction = setUpLoadDirection(mTagViewListModels?.tagViewBodel?.get(j ?: 0)?.tabText?.get(k)?.tags?.get(0)?.direction ?: 0)
                            mTagList?.type = 0

                            mTagList?.positionX = mTagViewListModels?.tagViewBodel?.get(j ?: 0)?.tabText?.get(k)?.percentX
                            mTagList?.positionY = mTagViewListModels?.tagViewBodel?.get(j ?: 0)?.tabText?.get(k)?.percentY


//                            mTagLists?.add(mTagList!!)
                            mBlogMultimediaList?.tagList?.add(mTagList!!)
                        }


                        mBlogMultimediaList?.sort = j
//                        mBlogMultimediaList?.tagList=mTagLists
                        mBlogMultimediaList?.url = it.result?.url

                        mUploadDataModel?.blogMultimediaList?.add(mBlogMultimediaList!!)
                        dd = uploadImageI(j ?: 0)
                        RxBus.getDefault().post(dd)
                    } else {
                        if (it.code.equals("000002")) {
                            dismissCompressDialog()
                            val intent = Intent(this, SecondActivity::class.java)
                            intent.putExtra("url", Constants.LOGIN_ADDRESS)
                            startActivity(intent)
                        } else {
                            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
                        }

                    }
                },{
                    it.printStackTrace()
                    if (it.message.equals("该操作需要用户登录")) {
                        val intent = Intent(this, SecondActivity::class.java)
                        intent.putExtra("url", Constants.LOGIN_ADDRESS)
                        startActivity(intent)
                    }
                    Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
                })
    }

    override fun onCheckedChanged(group: RadioGroup, @IdRes checkedId: Int) {

    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {

    }


    fun goPictureSelectorActivity() {
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(this@ReleaseActivity)
                .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(
                        PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .previewVideo(false)// 是否可预览视频
                .enablePreviewAudio(false) // 是否可播放音频
                .isCamera(false)// 是否显示拍照按钮FF
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩F
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .selectionMedia(selectList)// 是否传入已选图片
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST)//结果回调onActivityResult code
    }

    fun finishCameraActivity() {
        RxBus.getDefault().post("mteuskl")
        CameraActivity.mCameraActivity?.finish()
    }


    /**
     * compress loading dialog
     */
    protected fun showCompressDialog() {
        if (!isFinishing) {

            compressDialog = PictureDialog(this)
            compressDialog?.show()
        }
    }

    override fun onRestart() {
        super.onRestart()
        if (selectList.size == 0) {
            this.finish()
        }
    }
    /**
     * dismiss compress dialog
     */
    protected fun dismissCompressDialog() {
        try {
            if (!isFinishing
                    && compressDialog != null
                    && compressDialog!!.isShowing()) {
                compressDialog?.dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }
}
